package niit.game;

import android.graphics.Bitmap;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class GameControls implements OnTouchListener{


	public Point _touchingPoint = new Point(Main.SCREENWIDTH/3, Main.SCREENHEIGHT/3);
	private Boolean _dragging = false;
	int dx =-1,dy=-1;
	private int countEvent=0;
	public int pointNavigate=-1;
	
	private GameView gv;
	private Bitmap gun;
	
	
	public GameControls(GameView gameview,Bitmap Gun)
	{
		this.gv = gameview;
		this.gun=Gun;

	}
	
	public boolean onTouch(View v, MotionEvent event) {
		countEvent=event.getPointerCount();
		if(pointNavigate==-1)
		update(event);
		return true;
	}

	private MotionEvent lastEvent;
	public void update(MotionEvent event){

		if (event == null && lastEvent == null)
		{
			return;
		}else if(event == null && lastEvent != null){
			event = lastEvent;
		}else{
			lastEvent = event;
		}
		//drag drop 
		if(event.findPointerIndex(pointNavigate)==-1)
		{
			_dragging = false;
		}
		
		if ( event.getAction() == MotionEvent.ACTION_UP ){
			_dragging = false;
			dx = -1;
			pointNavigate=-1;
		}else {
			if(pointNavigate==-1)
			{
				for(int i =0 ; i< countEvent;i++)
				if(event.getX(i)>=MyPlane.PlanePoint.x&&event.getX(i)<=MyPlane.PlanePoint.x+MyPlane.plan.getWidth()&&event.getY(i)>=MyPlane.PlanePoint.y&&event.getY(i)<=MyPlane.PlanePoint.y+MyPlane.plan.getHeight())
				{
					pointNavigate = event.getPointerId(i);
					_dragging = true;
				}
			}
			
		}
		

		if ( _dragging ){
			// get the pos
			if(event.findPointerIndex(pointNavigate)!=-1)
			{		
				_touchingPoint.x =(int)event.getX(event.findPointerIndex( pointNavigate));
				_touchingPoint.y =(int)event.getY(event.findPointerIndex( pointNavigate));
				if(dx==-1){
				dx = _touchingPoint.x-	MyPlane.PlanePoint.x ;
				dy = _touchingPoint.y-	MyPlane.PlanePoint.y ;
				}
			}
				

				if(event.findPointerIndex(pointNavigate)!=-1)
				{
					MyPlane.PlanePoint.y =_touchingPoint.y -dy;
					MyPlane.PlanePoint.x =_touchingPoint.x -dx;
				}

				//make the pointer go thru
				if ( MyPlane.PlanePoint.x > gv.getWidth()-gun.getWidth())
				{
					MyPlane.PlanePoint.x= gv.getWidth()-gun.getWidth();										
				}
				if ( MyPlane.PlanePoint.x < 0){
					MyPlane.PlanePoint.x = 0;
				}
				if (MyPlane.PlanePoint.y > gv.getHeight()-gun.getHeight() ){
					MyPlane.PlanePoint.y = gv.getHeight()-gun.getHeight();
				}
				if (MyPlane.PlanePoint.y < 0){
					MyPlane.PlanePoint.y = 0;
				}		

			
		}else if (!_dragging)
		{
		}
	}
}
